{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import io\n",
    "import random\n",
    "import re\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_data(data_file): # charVocab is a char-to-idx dictionary:{char:idx}\n",
    "    with open(data_file, \"r\") as fr:\n",
    "        data = [line.split('\\t') for line in fr]\n",
    "    labels = ['体育', '娱乐', '家居', '彩票', '房产', '教育', '时尚', '时政', '星座', '游戏', '社会', '科技', '股票', '财经']\n",
    "    labels_dic = {item:idx for idx, item in enumerate(labels)}\n",
    "    data = [(item[1], labels_dic[item[0]]) for item in data]\n",
    "    return data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = ['体育', '娱乐', '家居', '彩票', '房产', '教育', '时尚', '时政', '星座', '游戏', '社会', '科技', '股票', '财经']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class THUReader:\n",
    "    def __init__(self, dataset, batchsize, tokenizer=None):\n",
    "        length = len(dataset)\n",
    "        self.length = (length//batchsize)*batchsize\n",
    "        \n",
    "        self.label = np.zeros([self.length, 14])\n",
    "        [self.label.itemset((idx, int(item[1])), 1) for (idx,item) in enumerate(dataset[:self.length])]\n",
    "        \n",
    "        if tokenizer is not None:\n",
    "            self.words = np.array([ \n",
    "                    tokenizer.encode(item[0], add_special_tokens=True)\n",
    "                    for item in dataset[:self.length]\n",
    "            ])\n",
    "        else:\n",
    "            self.words = np.array([self.text2words(item[0]) for item in dataset[:self.length]])\n",
    "        self.words_num = np.array([len(text) for text in self.words])\n",
    "        self.max_sent_len = max(self.words_num)\n",
    "        ##################convert into data batchs#################\n",
    "        self.words = self.words.reshape(-1, batchsize)\n",
    "        self.label = self.label.reshape(-1, batchsize, 3)\n",
    "        self.words_num = self.words_num.reshape(-1, batchsize)\n",
    "\n",
    "    def text2words(self, text):\n",
    "        rep_dic = {'1':'one ', \n",
    "                   '2':'two ', \n",
    "                   '3':'three ', \n",
    "                   '4':'four ', \n",
    "                   '5':'fine ', \n",
    "                   '6':'six ', \n",
    "                   '7':'seven ', \n",
    "                   '8':'eight ', \n",
    "                   '9':'nine ', \n",
    "                   '0':'zero '}\n",
    "        for k, v in rep_dic.items():\n",
    "            text = text.replace(k, v)\n",
    "        words = re.split('(?:[^a-zA-Z]+)', text.lower().strip() )\n",
    "        return words\n",
    "        \n",
    "    def reset_batchsize(self, new_batch_size):\n",
    "        _, _, label_num = self.label.shape\n",
    "        self.words = self.words.reshape(-1, new_batch_size)\n",
    "        self.label = self.label.reshape(-1, new_batch_size, label_num)\n",
    "        self.words_num = self.words_num.reshape(-1, new_batch_size)\n",
    "    \n",
    "    def sample(self):\n",
    "        batches, _, _ = self.label.shape\n",
    "        batch_idx = random.randint(0, batches-1)\n",
    "        return self.words[batch_idx], self.label[batch_idx], self.words_num[batch_idx]\n",
    "    \n",
    "    def iter(self):\n",
    "        for x, y, l in zip(self.words, self.label, self.words_num):\n",
    "            yield x, y, l "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import random\n",
    "import re\n",
    "import numpy as np\n",
    "import io\n",
    "\n",
    "\n",
    "\n",
    "def load_data(data_file): # charVocab is a char-to-idx dictionary:{char:idx}\n",
    "    with open(data_file, \"r\") as fr:\n",
    "        data = [line.split('\\t') for line in fr]\n",
    "    labels = ['体育', '娱乐', '家居', '彩票', '房产', '教育', '时尚', '时政', '星座', '游戏', '社会', '科技', '股票', '财经']\n",
    "    labels_dic = {item:idx for idx, item in enumerate(labels)}\n",
    "    data = [(item[1], labels_dic[item[0]]) for item in data]\n",
    "    return data\n",
    "\n",
    "def convert_sentence(max_seq_length, tokenizer, text):\n",
    "    if len(text)<(max_seq_length - 2):\n",
    "        texts = \"[CLS]%s[SEP]\"%text\n",
    "    else:\n",
    "        texts = \"[CLS]%s[SEP]\"%text[:(max_seq_length - 2)]\n",
    "        \n",
    "    input_ids = tokenizer.encode(texts)\n",
    "    if len(input_ids)<max_seq_length:\n",
    "        segment_ids = [0] * len(input_ids)\n",
    "        input_mask = [1] * len(input_ids)\n",
    "        while len(input_ids) < max_seq_length:\n",
    "            input_ids.append(0)\n",
    "            input_mask.append(0)\n",
    "            segment_ids.append(0)\n",
    "    else:\n",
    "        input_ids = input_ids[:max_seq_length]\n",
    "        segment_ids = [0] * len(input_ids)\n",
    "        input_mask = [1] * len(input_ids)\n",
    "    assert len(input_ids) == max_seq_length\n",
    "    assert len(input_mask) == max_seq_length\n",
    "    assert len(segment_ids) == max_seq_length\n",
    "    return input_ids,input_mask,segment_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "class THUReader:\n",
    "    def __init__(self, dataset, batchsize, max_seq_length, tokenizer=None):\n",
    "        length = len(dataset)\n",
    "        self.length = (length//batchsize)*batchsize\n",
    "        self.max_seq_length = max_seq_length\n",
    "        self.label_ids = np.zeros([self.length])\n",
    "        ipt_ids, ipt_masks, seg_ids = [], [], []\n",
    "        for (idx,item) in enumerate(dataset[:self.length]):\n",
    "            self.label_ids[idx] = item[1]\n",
    "            ipt_id, ipt_mask, seg_id = convert_sentence(max_seq_length, tokenizer, item[0])\n",
    "            ipt_ids.append(ipt_id)\n",
    "            ipt_masks.append(ipt_mask)\n",
    "            seg_ids.append(seg_id)\n",
    "        ##################convert into data batchs#################\n",
    "        self.label_ids = self.label_ids.reshape(-1, batchsize)\n",
    "        self.input_ids = np.array(ipt_ids).reshape(-1, batchsize, max_seq_length)\n",
    "        self.input_masks = np.array(ipt_masks).reshape(-1, batchsize, max_seq_length)\n",
    "        self.segment_ids = np.array(seg_ids).reshape(-1, batchsize, max_seq_length)\n",
    "  \n",
    "    def reset_batchsize(self, new_batch_size):\n",
    "        self.input_ids = self.input_ids.reshape(-1, new_batch_size, self.max_seq_length)\n",
    "        self.label_ids = self.label_ids.reshape(-1, new_batch_size)\n",
    "        self.input_masks = self.input_masks.reshape(-1, new_batch_size, self.max_seq_length)\n",
    "        self.segment_ids = self.segment_ids.reshape(-1, new_batch_size, self.max_seq_length)\n",
    "    \n",
    "    def sample(self):\n",
    "        batches, _, _ = self.label.shape\n",
    "        batch_idx = random.randint(0, batches-1)\n",
    "        return self.input_ids[batch_idx], self.label_ids[batch_idx], self.segment_ids[batch_idx], self.input_masks[batch_idx]\n",
    "    \n",
    "    def iter(self):\n",
    "        for x, y, s, m in zip(self.input_ids, self.label_ids, self.segment_ids, self.input_masks):\n",
    "            yield x, y, s, m "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_file = './THUCnews/cnews.test.txt'\n",
    "val_file = './THUCnews/cnews.val.txt'\n",
    "train_file = './THUCnews/cnews.train.txt'\n",
    "val_data = load_data(\"./THUCnews/cnews.val.txt\")\n",
    "tr_data = load_data(train_file)\n",
    "te_data = load_data(test_file)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import BertTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = BertTokenizer.from_pretrained(\"publish/\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "val_reader = THUReader(val_data, 20, 512, tokenizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'THUReader' object has no attribute 'label'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-20-90c61b2874f3>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mm\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mval_reader\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msample\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-18-c27fdbeb85ea>\u001b[0m in \u001b[0;36msample\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m     25\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     26\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0msample\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 27\u001b[0;31m         \u001b[0mbatches\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlabel\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     28\u001b[0m         \u001b[0mbatch_idx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrandom\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrandint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbatches\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     29\u001b[0m         \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minput_ids\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mbatch_idx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlabel_ids\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mbatch_idx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msegment_ids\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mbatch_idx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minput_masks\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mbatch_idx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAttributeError\u001b[0m: 'THUReader' object has no attribute 'label'"
     ]
    }
   ],
   "source": [
    "x, y, s, m = val_reader.sample()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# labels = ['体育', '娱乐', '家居', '彩票', '房产', '教育', '时尚', '时政', '星座', '游戏', '社会', '科技', '股票', '财经']\n",
    "\n",
    "# len(labels)\n",
    "\n",
    "# label_cnt = [0]*14\n",
    "\n",
    "# sample_labels =[]\n",
    "# x = []\n",
    "# for (text, label_idx) in val_data:\n",
    "#     x.append(label_idx)\n",
    "#     if label_cnt[label_idx] == 0:\n",
    "#         print(label_idx)\n",
    "#         with open(\"%s.txt\"%labels[label_idx], \"w\") as fw:\n",
    "#             fw.write(text)\n",
    "#         label_cnt[label_idx] +=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# with open(\"\", encoding=\"utf-8\") as f:\n",
    "with io.open('./THUCnews/cnews.val.txt','r',encoding='utf-8') as f:\n",
    "    for line in f:\n",
    "        t_line = line\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = ['体育', '娱乐', '家居', '彩票', '房产', '教育', '时尚', '时政', '星座', '游戏', '社会', '科技', '股票', '财经']\n",
    "labels_dic = {item:idx for idx, item in enumerate(labels)}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
